package com.example.thymeleaf.servlet;

import com.example.thymeleaf.bean.User;
import com.example.thymeleaf.service.UserService;
import com.example.thymeleaf.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author ddone
 * @date 2024/3/13-20:17
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet{
    private UserService userService = new UserServiceImpl();

    /**
     * 添加用户的数据
     * @param req
     * @param resp
     * @throws IOException
     */
    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = new User();
        try {
            BeanUtils.populate(user, req.getParameterMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
        int rows = userService.insertUser(user);
        resp.sendRedirect(req.getContextPath()+"/user?method=findUsers");
    }

    /**
     * 按照ID删除用户数据
     * @param req
     * @param resp
     * @throws IOException
     */
    public void deleteById(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String userid = req.getParameter("userid");
        int rows = userService.deleteById(userid);
        resp.sendRedirect(req.getContextPath()+"/user?method=findUsers");
    }

    /**
     * 按照ID查询用户
     * @param req
     * @param resp
     * @throws IOException
     */
    public void findUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = userService.findUserById(req.getParameter("userid"));
        req.setAttribute("updateUser",user);
        this.processTemplate("crud",req,resp);
    }

    /**
     * 查询所有用户
     * @param req
     * @param resp
     * @throws IOException
     */
    public void findUsers(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<User> userList = userService.findUserList();
        req.setAttribute("userList",userList);
        this.processTemplate("crud",req,resp);
    }

    public void updateUser(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        User user = new User();
        try {
            BeanUtils.populate(user,req.getParameterMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
        int rows = userService.updateUser(user);
        resp.sendRedirect(req.getContextPath()+"/user?method=findUsers");
    }

}
